package com.example.weiting.huishenghuo.com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.weiting.huishenghuo.R;
import com.example.weiting.huishenghuo.utils.User;

import java.io.Serializable;
import java.util.ArrayList;


public class Register extends AppCompatActivity {
    EditText username,password;
    Button register;
    ArrayList<User> users;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        //读取主界面传来的用户信息（代替数据库的作用）
        Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("users");
        users = (ArrayList<User>) args.getSerializable("userList");

        //获取相应组件
        username = (EditText) findViewById(R.id.userName1);
        password = (EditText) findViewById(R.id.password1);
        register = (Button) findViewById(R.id.zhuce);
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Boolean t = true;
                if( username.getText().toString().trim().length() == 0) {
                    t = false;
                    Toast.makeText(Register.this, "请输入用户名！", Toast.LENGTH_SHORT).show();
                }
                if( password.getText().toString().trim().length() == 0){
                    t = false;
                    Toast.makeText(Register.this, "请输入密码！", Toast.LENGTH_SHORT).show();
                }
                for (User u:users
                     ) {
                    if(username.getText().toString().equals(u.getUsername())){
                        t = false;
                        Toast.makeText(Register.this, "用户名已存在！", Toast.LENGTH_SHORT).show();
                    }
                }
                if(t) {
                    User user = new User();
                    user.setUsername(username.getText().toString());
                    user.setPassworld(password.getText().toString());
                    users.add(user);
                    //注册成功，跳转到登陆页面，同时将users传入。
                    Intent intent = new Intent(Register.this, Login.class);
                    Bundle args = new Bundle();
                    args.putSerializable("userList", (Serializable) users);
                    intent.putExtra("users", args);
                    startActivity(intent);
                }
            }
        });
    }
}
